package service

import (
	"errors"
	"fmt"
	"os"
	"sort"
)

// GetLatestFile 获取最新文件
func GetLatestFile(path string) (os.FileInfo, error) {
	fmt.Println(path)
	//仅当前文件夹，不递归
	fileInfoList, err := os.ReadDir(path)
	if err != nil {
		fmt.Println("读取文件夹错误")
		return nil, err
	}
	if len(fileInfoList) == 0 {
		return nil, errors.New("找不到文件")
	}
	sort.Slice(fileInfoList, func(i, j int) bool {
		filei, err := fileInfoList[i].Info()
		if err != nil {
			return false
		}
		filej, err := fileInfoList[j].Info()
		if err != nil {
			return false
		}
		return filei.ModTime().Sub(filej.ModTime()) > 0
	})
	return fileInfoList[0].Info()
}
